<template>
  <view class="index-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input" @click="goToSearch">
        <uv-icon name="search" size="16" color="#999"></uv-icon>
        <text class="search-placeholder">搜索商品</text>
      </view>
      <view class="location" @click="chooseLocation">
        <uv-icon name="map" size="16" color="#FF6B00"></uv-icon>
        <text class="location-text">{{ location }}</text>
        <uv-icon name="arrow-down" size="12" color="#999"></uv-icon>
      </view>
    </view>

    <!-- 公告栏 -->
    <view class="notice-section">
      <uv-notice-bar :text="noticeText" mode="horizontal" color="#666" bgColor="#fff" :speed="80"></uv-notice-bar>
    </view>

    <!-- 分类快捷入口 -->
    <view class="category-quick" v-if="categories.length">
      <view class="quick-grid">
        <view class="quick-item" v-for="item in categories.slice(0,8)" :key="item.id" @click="goToCategory(item)">
          <image :src="item.icon || item.image || DEFAULT_CATEGORY_ICON" class="quick-icon" mode="aspectFill"></image>
          <text class="quick-name">{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section">
      <swiper class="banner-swiper" indicator-dots autoplay circular>
        <swiper-item v-for="banner in homeData.banners" :key="banner.id">
          <image :src="banner.image" class="banner-image" mode="aspectFill" @click="handleBannerClick(banner)"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 限时秒杀 -->
    <view class="seckill-section" v-if="homeData.seckill">
      <view class="section-header">
        <view class="section-title">
          <text class="title-text">{{ homeData.seckill.title }}</text>
          <view class="countdown">
            <text class="countdown-text">距结束</text>
            <uv-count-down :timestamp="seckillEndTime" format="HH:mm:ss"></uv-count-down>
          </view>
        </view>
        <view class="more-btn" @click="goToSeckill">
          <text>更多</text>
          <uv-icon name="arrow-right" size="12" color="#999"></uv-icon>
        </view>
      </view>
      <scroll-view class="seckill-scroll" scroll-x>
        <view class="seckill-item" v-for="item in homeData.seckill.goods" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="seckill-image" mode="aspectFill"></image>
          <view class="seckill-info">
            <text class="seckill-name">{{ item.name }}</text>
            <view class="seckill-price">
              <text class="current-price">¥{{ item.seckill_price }}</text>
              <text class="original-price">¥{{ item.original_price }}</text>
            </view>
            <view class="seckill-progress">
              <view class="progress-bar">
                <view class="progress-fill" :style="{ width: getProgressWidth(item) }"></view>
              </view>
              <text class="progress-text">已抢{{ item.sold_count }}/{{ item.stock }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 团长推荐 -->
    <view class="recommend-section" v-if="homeData.recommend">
      <view class="section-header">
        <text class="section-title">{{ homeData.recommend.title }}</text>
        <view class="more-btn" @click="goToLeaderList">
          <text>更多团长</text>
          <uv-icon name="more-dot-fill" size="12" color="#999"></uv-icon>
        </view>
      </view>
      <view class="recommend-list">
        <view class="recommend-item" v-for="item in homeData.recommend.goods" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="recommend-image" mode="aspectFill"></image>
          <view class="recommend-info">
            <text class="recommend-name">{{ item.name }}</text>
            <view class="recommend-price">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="original-price">¥{{ item.original_price }}</text>
            </view>
            <view class="leader-info">
              <image :src="item.leader_avatar" class="leader-avatar" mode="aspectFill"></image>
              <text class="leader-name">{{ item.leader_name }}</text>
              <text class="commission-rate">佣金{{ item.commission_rate }}%</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 品牌专区 -->
    <view class="brand-section" v-if="brandList.length">
      <view class="section-header">
        <text class="section-title">品牌专区</text>
      </view>
      <view class="brand-list">
        <view class="brand-item" v-for="item in brandList" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="brand-image" mode="aspectFill"></image>
          <view class="brand-info">
            <text class="brand-name">{{ item.name }}</text>
            <text class="brand-price">¥{{ item.price }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 爆款榜单 -->
    <view class="hot-section" v-if="hotList.length">
      <view class="section-header">
        <text class="section-title">爆款榜单</text>
      </view>
      <view class="hot-list">
        <view class="hot-item" v-for="item in hotList" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="hot-image" mode="aspectFill"></image>
          <view class="hot-info">
            <text class="hot-name">{{ item.name }}</text>
            <view class="hot-price">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="original-price" v-if="item.original_price">¥{{ item.original_price }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 猜你喜欢 -->
    <view class="guess-section" v-if="guessList.length">
      <view class="section-header">
        <text class="section-title">猜你喜欢</text>
      </view>
      <view class="guess-grid">
        <view class="guess-item" v-for="item in guessList" :key="item.id" @click="goToGoodsDetail(item.id)">
          <image :src="item.image" class="guess-image" mode="aspectFill"></image>
          <view class="guess-info">
            <text class="guess-name">{{ item.name }}</text>
            <view class="guess-price">
              <text class="current-price">¥{{ item.price }}</text>
              <text class="original-price" v-if="item.original_price">¥{{ item.original_price }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="guess-more">
        <text class="more-text" v-if="guessLoading">加载中...</text>
        <text class="more-text" v-else-if="!guessHasMore">没有更多了</text>
      </view>
    </view>

    <!-- 底部导航提示 -->
    <view class="bottom-tips">
      <text class="tips-text">惠聚邻里，购享生活</text>
    </view>
  </view>
</template>

<script setup>
// 采用 Vue3 <script setup> 语法重构（中文注释，变量/函数使用英文）
import { ref, reactive, getCurrentInstance } from 'vue'
import { onLoad, onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { goodsApi } from '../../api/index.js'

// 全局方法（如 $navigateTo/$showToast）通过 proxy 访问
const { proxy } = getCurrentInstance()

// 状态
const location = ref('定位中...')
const homeData = reactive({
  banners: [],
  seckill: null,
  recommend: null
})
const seckillEndTime = ref(0)
// 分类与猜你喜欢
const categories = ref([])
const guessList = ref([])
const guessPage = ref(1)
const guessPageSize = ref(10)
const guessHasMore = ref(true)
const guessLoading = ref(false)

// 品牌与爆款
const brandList = ref([])
const hotList = ref([])

// 公告文案（后端返回）
const noticeText = ref('')
// 分类图标占位（SVG）
const DEFAULT_CATEGORY_ICON = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="88" height="88" viewBox="0 0 88 88"><rect width="88" height="88" rx="18" fill="%23f7f7f7"/><g fill="%23FF6B00"><circle cx="22" cy="22" r="8"/><circle cx="66" cy="22" r="8"/><circle cx="22" cy="66" r="8"/><circle cx="66" cy="66" r="8"/></g></svg>'

// 初始化页面
const initPage = async () => {
  uni.showLoading({ title: '加载中...' })
  try {
    const data = await goodsApi.getHomeGoods()
    homeData.banners = data.banners || []
    homeData.seckill = data.seckill || null
    homeData.recommend = data.recommend || null
    // 公告（优先后端返回）
    noticeText.value = data.notice || data.notice_text || noticeText.value || '惠聚邻里，购享生活'

    // 计算秒杀结束时间
    if (data.seckill && data.seckill.end_time) {
      seckillEndTime.value = new Date(data.seckill.end_time).getTime()
    }


    // 并发获取分类、品牌、爆款
    const [catRes, brandRes, hotRes] = await Promise.all([
      goodsApi.getCategories(),
      goodsApi.searchGoods({ page: 1, page_size: 6, keyword: '品牌' }),
      goodsApi.searchGoods({ page: 1, page_size: 6, keyword: '爆款' })
    ])
    categories.value = Array.isArray(catRes) ? catRes : (catRes?.data || [])
    brandList.value = (brandRes && (brandRes.list || brandRes.data?.list)) || []
    hotList.value = (hotRes && (hotRes.list || hotRes.data?.list)) || []

    // 初始化猜你喜欢
    resetGuess()
    await loadGuessList()
  } catch (error) {
    proxy?.$showToast?.('加载失败')
  } finally {
    uni.hideLoading()
  }
}

// 获取位置信息
const getLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: () => {
      // 这里应该调用逆地理编码接口获取地址
      location.value = '北京市朝阳区'
    },
    fail: () => {
      location.value = '定位失败'
    }
  })
}

// 选择位置
const chooseLocation = () => {
  uni.chooseLocation({
    success: (res) => {
      location.value = res.name
    }
  })
}

// 路由跳转
const goToSearch = () => {
  proxy?.$navigateTo?.('/pages/search/index')
}
const goToSeckill = () => {
  proxy?.$navigateTo?.('/pages/seckill/index')
}
const goToLeaderList = () => {
  proxy?.$navigateTo?.('/pages/leader/list')
}
const goToGoodsDetail = (id) => {
  proxy?.$navigateTo?.(`/pages/goods/detail?id=${id}`)
}
const goToCategory = (item) => {
  const id = item?.id
  if (id) {
    proxy?.$navigateTo?.(`/pages/category/index?id=${id}`)
  } else {
    proxy?.$navigateTo?.('/pages/category/index')
  }
}

// 处理轮播图点击
const handleBannerClick = (banner) => {
  if (banner.link) {
    proxy?.$navigateTo?.(banner.link)
  }
}

// 猜你喜欢分页
const resetGuess = () => {
  guessPage.value = 1
  guessHasMore.value = true
  guessList.value = []
}
const loadGuessList = async () => {
  if (!guessHasMore.value || guessLoading.value) return
  guessLoading.value = true
  try {
    const res = await goodsApi.searchGoods({ page: guessPage.value, page_size: guessPageSize.value })
    const list = (res && (res.list || res.data?.list)) || []
    if (list.length < guessPageSize.value) {
      guessHasMore.value = false
    }
    guessList.value = guessList.value.concat(list)
    guessPage.value += 1
  } finally {
    guessLoading.value = false
  }
}

onReachBottom(() => {
  loadGuessList()
})

// 下拉刷新：重载首页 & 猜你喜欢
onPullDownRefresh(async () => {
  resetGuess()
  await initPage()
  uni.stopPullDownRefresh()
})

// 计算进度条宽度
const getProgressWidth = (item) => {
  const progress = (item.sold_count / item.stock) * 100
  return Math.min(progress, 100) + '%'
}

// 生命周期
onLoad(() => {
  console.log('[index][onLoad]')
  initPage()
})
onShow(() => {
  console.log('[index][onShow]')
  getLocation()
})
</script>

<style lang="scss" scoped>
.index-container {
  min-height: 100vh;
  background-color: $uni-bg-color-grey;
}

.notice-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid $uni-border-color;
  box-shadow: 0 6rpx 18rpx rgba(0,0,0,0.04);
  
  .search-input {
    flex: 1;
    display: flex;
    align-items: center;
    height: 70rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 35rpx;
    margin-right: 20rpx;
    
    .search-placeholder {
      margin-left: 10rpx;
      color: #999;
      font-size: 28rpx;
    }
  }
  
  .location {
    display: flex;
    align-items: center;
    
    .location-text {
      margin: 0 10rpx;
      color: #333;
      font-size: 28rpx;
    }
  }
}

.banner-section {
  .banner-swiper {
    height: 300rpx;
    
    .banner-image {
      width: 100%;
      height: 100%;
    }
  }
}

.category-quick {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  padding: 24rpx 16rpx 12rpx;

  .quick-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16rpx 8rpx;
  }

  .quick-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 12rpx 0;
    transition: transform 0.12s ease-out;
    -webkit-tap-highlight-color: transparent;
    &:active { transform: scale(0.96); }
  }

  .quick-icon {
    width: 88rpx;
    height: 88rpx;
    border-radius: 18rpx;
    background: #f7f7f7;
    border: 1rpx solid $uni-border-color;
    box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
    margin-bottom: 10rpx;
  }

  .quick-name {
    font-size: 24rpx;
    color: #333;
    max-width: 140rpx;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.seckill-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      display: flex;
      align-items: center;
      
      .title-text {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 20rpx;
      }
      
      .countdown {
        display: flex;
        align-items: center;
        
        .countdown-text {
          font-size: 24rpx;
          color: #666;
          margin-right: 10rpx;
        }
      }
    }
    
    .more-btn {
      display: flex;
      align-items: center;
      color: #999;
      font-size: 24rpx;
    }
  }
  
  .seckill-scroll {
    white-space: nowrap;
    
    .seckill-item {
      display: inline-block;
      width: 200rpx;
      margin-right: 20rpx;
      
      .seckill-image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 10rpx;
      }
      
      .seckill-info {
        padding: 10rpx 0;
        
        .seckill-name {
          font-size: 26rpx;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .seckill-price {
          margin: 10rpx 0;
          
          .current-price {
            font-size: 28rpx;
            color: $uni-color-primary;
            font-weight: bold;
            margin-right: 10rpx;
          }
          
          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
          }
        }
        
        .seckill-progress {
          .progress-bar {
            height: 6rpx;
            background-color: #f0f0f0;
            border-radius: 3rpx;
            overflow: hidden;
            margin-bottom: 5rpx;
            
            .progress-fill {
              height: 100%;
              background-color: $uni-color-primary;
              transition: width 0.3s;
            }
          }
          
          .progress-text {
            font-size: 20rpx;
            color: #999;
          }
        }
      }
    }
  }
}

.recommend-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .more-btn {
      display: flex;
      align-items: center;
      color: #999;
      font-size: 24rpx;
    }
  }
  
  .recommend-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    
    .recommend-item {
      .recommend-image {
        width: 100%;
        height: 300rpx;
        border-radius: 10rpx;
      }
      
      .recommend-info {
        padding: 15rpx 0;
        
        .recommend-name {
          font-size: 28rpx;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .recommend-price {
          margin: 10rpx 0;
          
          .current-price {
            font-size: 30rpx;
            color: $uni-color-primary;
            font-weight: bold;
            margin-right: 10rpx;
          }
          
          .original-price {
            font-size: 24rpx;
            color: #999;
            text-decoration: line-through;
          }
        }
        
        .leader-info {
          display: flex;
          align-items: center;
          
          .leader-avatar {
            width: 40rpx;
            height: 40rpx;
            border-radius: 50%;
            margin-right: 10rpx;
          }
          
          .leader-name {
            font-size: 24rpx;
            color: #666;
            margin-right: 10rpx;
          }
          
          .commission-rate {
            font-size: 22rpx;
            color: $uni-color-primary;
            background-color: #fff5e6;
            padding: 2rpx 8rpx;
            border-radius: 10rpx;
          }
        }
      }
    }
  }
}

.brand-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .brand-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }

  .brand-item {
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    border: 1rpx solid $uni-border-color;
    box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
  }

  .brand-image {
    width: 100%;
    height: 260rpx;
  }

  .brand-info {
    padding: 16rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .brand-name {
      font-size: 28rpx;
      color: #333;
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-right: 10rpx;
    }

    .brand-price {
      font-size: 30rpx;
      color: $uni-color-primary;
      font-weight: 600;
    }
  }
}

.hot-section {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .hot-list {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20rpx;
  }

  .hot-item {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    border: 1rpx solid $uni-border-color;
    box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
    padding: 12rpx;
  }

  .hot-image {
    width: 200rpx;
    height: 200rpx;
    border-radius: 12rpx;
    margin-right: 16rpx;
  }

  .hot-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .hot-name {
      font-size: 28rpx;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 10rpx;
    }

    .hot-price {
      .current-price {
        font-size: 32rpx;
        color: $uni-color-primary;
        font-weight: 600;
        margin-right: 12rpx;
      }
      .original-price {
        font-size: 24rpx;
        color: #aaa;
        text-decoration: line-through;
      }
    }
  }
}

.guess-section {
  margin: 20rpx;
  padding: 30rpx 30rpx 10rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 12rpx 32rpx rgba(0,0,0,0.06);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .guess-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }

  .guess-item {
    background: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    border: 1rpx solid $uni-border-color;
    box-shadow: 0 8rpx 22rpx rgba(0,0,0,0.05);
  }

  .guess-image {
    width: 100%;
    height: 300rpx;
  }

  .guess-info {
    padding: 16rpx;

    .guess-name {
      font-size: 28rpx;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-bottom: 10rpx;
    }

    .guess-price {
      .current-price {
        font-size: 30rpx;
        color: $uni-color-primary;
        font-weight: 600;
        margin-right: 10rpx;
      }
      .original-price {
        font-size: 24rpx;
        color: #aaa;
        text-decoration: line-through;
      }
    }
  }

  .guess-more {
    text-align: center;
    padding: 16rpx 0 6rpx;
    .more-text {
      font-size: 24rpx;
      color: #999;
    }
  }
}

.bottom-tips {
  text-align: center;
  padding: 40rpx 0;
  
  .tips-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>
